const { createApp } = Vue

// 配置 axios 默认值
axios.defaults.baseURL = '/api';
axios.defaults.timeout = 10000;
axios.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded';

// 创建 axios 实例并配置拦截器
const http = axios.create();

// 请求拦截器
http.interceptors.request.use(config => {
    const token = localStorage.getItem('token');
    if (!token) {
        window.location.href = '/login.html';
        return Promise.reject('未登录');
    }
    config.headers['Authorization'] = token;

    // 将请求参数转换为表单格式，避免预检
    if (config.data) {
        config.data = Object.keys(config.data)
            .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(config.data[key])}`)
            .join('&');
    }
    return config;
});

// 响应拦截器
http.interceptors.response.use(
    response => {
        if (response.data.code !== "200") {
            throw new Error(response.data.message || '请求失败');
        }
        return response;
    },
    error => {
        if (error.response?.status === 401) {
            localStorage.removeItem('token');
            window.location.href = '/login.html';
        }
        return Promise.reject(error);
    }
);

createApp({
    data() {
        return {
            therapist: {
                name: '',
                avatar: '',
                title: '',
                totalClients: 0
            },
            stats: {
                todayAppointments: 0,
                weeklyConsultations: 0,
                totalClients: 0,
                satisfaction: 0
            },
            todaySchedule: [],
            loading: {
                profile: false,
                stats: false,
                schedule: false
            },
            error: null,
            refreshTimer: null,
            showCancelModal: false,
            selectedAppointment: null
        }
    },
    methods: {
        // 获取咨询师基本信息
        async fetchTherapistInfo() {
            this.loading.profile = true;
            try {
                const response = await http.get('/therapist/profile');
                const data = response.data.data;
                this.therapist = {
                    name: data.name || '未知咨询师',
                    avatar: data.gender === 'female' ? '/images/therapist-female.svg' : '/images/therapist-male.svg',
                    title: data.title || '心理咨询师',
                    totalClients: data.totalClients || 0
                };
            } catch (error) {
                console.error('获取咨询师信息失败:', error);
                this.error = error.message;
            } finally {
                this.loading.profile = false;
            }
        },

        // 获取统计数据
        async fetchStats() {
            this.loading.stats = true;
            try {
                const response = await http.get('/therapist/stats');
                this.stats = response.data.data;
            } catch (error) {
                console.error('获取统计数据失败:', error);
                this.error = error.message;
            } finally {
                this.loading.stats = false;
            }
        },

        // 获取今日日程
        async fetchTodaySchedule() {
            try {
                this.loading.schedule = true;
                const response = await http.get('/therapist/schedule/today');

                // 处理每个预约的状态样式
                this.todaySchedule = response.data.data.map(appointment => ({
                    ...appointment,
                    statusClass: this.getStatusClass(appointment.status)
                }));
            } catch (error) {
                console.error('获取日程失败:', error);
                this.error = error.message;
            } finally {
                this.loading.schedule = false;
            }
        },

        // 刷新所有数据
        async refreshData() {
            try {
                await Promise.all([
                    this.fetchTherapistInfo(),
                    this.fetchStats(),
                    this.fetchTodaySchedule()
                ]);
            } catch (error) {
                console.error('刷新数据失败:', error);
            }
        },

        // 启动自动刷新
        startAutoRefresh() {
            this.refreshTimer = setInterval(() => {
                this.refreshData();
            }, 5 * 60 * 1000); // 每5分钟刷新一次
        },

        // 停止自动刷新
        stopAutoRefresh() {
            if (this.refreshTimer) {
                clearInterval(this.refreshTimer);
                this.refreshTimer = null;
            }
        },

        getStatusClass(status) {
            switch (status) {
                case 'pending':
                    return 'pending';
                case 'ongoing':
                    return 'ongoing';
                case 'completed':
                    return 'completed';
                case 'cancelled':
                    return 'cancelled';
                default:
                    return '';
            }
        },

        // 退出登录
        async logout() {
            try {
                // 调用登出接口
                await http.post('/auth/logout');
                // 清除本地存储的 token
                localStorage.removeItem('token');
                // 跳转到登录页
                window.location.href = '/login.html';
            } catch (error) {
                console.error('退出登录失败:', error);
                // 即使退出失败，也清除 token 并跳转
                localStorage.removeItem('token');
                window.location.href = '/login.html';
            }
        },

        showCancelDialog(appointment) {
            this.selectedAppointment = appointment;
            this.showCancelModal = true;
        },

        async cancelAppointment() {
            try {
                const response = await http.post(`/api/appointments/${this.selectedAppointment.id}/cancel`);

                if (response.data.code === "200") {
                    alert('预约已取消');
                    this.fetchTodaySchedule();
                    this.showCancelModal = false;
                } else {
                    throw new Error(response.data.message || '取消预约失败');
                }
            } catch (error) {
                console.error('取消预约失败:', error);
                alert(error.message || '取消预约失败，请稍后重试');
            }
        },

        closeCancelModal() {
            this.showCancelModal = false;
            this.selectedAppointment = null;
        }
    },
    created() {
        this.refreshData();
        this.startAutoRefresh();
    },
    beforeUnmount() {
        this.stopAutoRefresh();
    }
}).mount('#app') 